package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	fmt.Println("start goroutine...")
	var wg sync.WaitGroup
	var resChan = make(chan int)

	//启动多goroutine处理
	for i := 0; i < 3; i++ {
		wg.Add(1)
		go process(i, &wg, resChan)
	}

	//等待Goroutine
	go waitGoroutine(&wg, resChan)

	// 从通道接收所有结果
	for res := range resChan {
		fmt.Println("Result:", res)
	}
}

// 等待Goroutine
func waitGoroutine(wg *sync.WaitGroup, resChan chan<- int) {
	fmt.Println("waitting end...")
	wg.Wait()
	close(resChan)
	fmt.Println("end...")
}

// 异步处理
func process(i int, wg *sync.WaitGroup, resChan chan<- int) {
	defer wg.Done()
	fmt.Printf("running goroutine %d start... \n", i)
	time.Sleep(2 * time.Millisecond)
	fmt.Printf("running goroutine %d end... \n", i)
	resChan <- i
}
